'use strict';
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)
	
	
	
	let js_code = event.code  
	const appid = 'wx1f32e5c54df56771' //appid  
	const secret = '8fc390775b87b8a97f40655c2d99be1e' //secret  
	var loginUrl = 'https://api.weixin.qq.com/sns/jscode2session'   
	
	var  param = {
		
	}
	
	if(event.platform == 'WX'){
		loginUrl = 'https://api.weixin.qq.com/sns/jscode2session'   
		param = {  
			appid: appid,  
			secret: secret,  
			js_code: js_code,  
			grant_type: 'authorization_code'  
		  }
	}else if(event.platform == "TT"){
		loginUrl = 'https://minigame.zijieapi.com/mgplatform/api/apps/jscode2session'  
		 param = {
		 	appid: appid,  
		 	secret: secret,  
		 	code: js_code
		   }
	}
	
	let res = await uniCloud.httpclient.request(loginUrl, {  
	  data: param,  
	  dataType: 'json'  
	  }) 
	  
	  console.log('event res: ', JSON.stringify(res))
	  
	  
	const db = uniCloud.database();
	const collection = await db.collection('user_info');
	
	let res2 = await new Promise((resolve, reject)=>{
		let res1 = collection.where({
			"openid":res.data.openid,
		}).get();
		 
		res1.then(async (y)=>{
			console.log('y res1: ', JSON.stringify(y))
			if(y.data && y.data.length > 0){
				resolve({
					code:1,
					data:y.data[0]
				})
			}else{
				if(!res.data.openid){
					reject({"msg":'error'});
				}else{
					let data = {
						_id: res.data.openid,
						openid:res.data.openid,
						pass:0,
						session_key:res.data.session_key,
						nickname:"",
						gold: 0
					}
					let result = await collection.add(
					  [
					     data
					   ]
					)
					console.log('result: ', JSON.stringify(result))
					resolve({
						code:1,
						data:data
					})
				}
				
				
			}
		})
		
		res1.catch((n)=>{
			reject({"msg":'error'});
		})
	})
	
	//返回数据给客户端
	return res2
};
